<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="24">
          <el-table
            :data="list.list"
            @selection-change="handleSelectionChange"
            :stripe="true"
            :show-overflow-="true"
          >
            <el-table-column type="selection" width="55" /><el-table-column
              align="center"
              prop="create_time"
              label="创建日期"
              sortable
            />
            <el-table-column
              v-for="(column, index) in list.columns"
              :key="index"
              :prop="column.prop"
              :label="column.label"
              align="center"
              :width="column.prop === 'id' ? 55 : ''"
            >
              <template #default="scope">
                <el-image
                  v-if="imaged(scope.row[column.prop])"
                  :src="buildImage(column.prop, scope.row)"
                  style="max-width: 50px"
                >
                  <template #error>
                    <el-image :src="bookLogo" style="max-width: 50px"></el-image>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="资源状态">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.RESOURCE_STATUS" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="230px">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  v-hasPermi="[
                    'resource:meta:update',
                    'resource:sps:update',
                    'resource:standard:update'
                  ]"
                  @click="updateResource(scope.row.id)"
                >
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :span="24">
          <el-form-item label="说明" prop="idea">
            <el-select
              v-model="formData.idea"
              clearable
              placeholder="请选择原因说明"
              @change="handleOptionChange(formData.idea)"
              size="large"
              placement="bottom"
            >
              <el-option
                v-for="item in options"
                :key="item.label"
                :label="item.value"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="danger" @click="submitAudit">驳 回</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <el-dialog
    v-model="showFormDialogFlag"
    :title="formTitle"
    left
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="85%"
    @close="closeForm"
    destroy-on-close
  >
    <v-form-render
      ref="vFormRef"
      :form-json="formJson"
      :form-data="formData"
      :option-data="optionData"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="closeForm">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import * as metaApi from '@/api/meta'
import * as pictureApi from '@/api/picture'
import * as videoApi from '@/api/video'
import * as audioApi from '@/api/audio'
import { DICT_TYPE } from '@/utils/dict'
import bookLogo from '@/assets/imgs/bookLogo.webp'
import * as AuditLogApi from '@/api/auditLog'

const formRef = ref() // 表单 Ref
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('重复资源列表') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const uri = window.location.href.split('/')
const id = Number(uri[uri.length - 1])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: 1,
  statusArr: [], //多状态标识
  keyword: null,
  author: null,
  press: null,
  createTime: []
})
const selectedItems = ref([])
const handleSelectionChange = (row) => {
  selectedItems.value = row
}

/** 原因选择 */
const options = [
  {
    value: '资源查重未通过',
    label: '资源查重未通过'
  },
  {
    value: '资源元数据信息缺失',
    label: '资源元数据信息缺失'
  },
  {
    value: '该资源不需要入库',
    label: '该资源不需要入库'
  },
  {
    value: '其他',
    label: '其他'
  }
]

const navigationals = ref([])
const leftSpan = ref(0)
const rightSpan = ref(24)
const fieldList = ref([])
const selectForm = async () => {
  let res = await metaApi.selectForm(id)
  let f = JSON.parse(res.tableForm)
  console.log(f)
  formJson.value.widgetList = f.widgetList
  formJson.value.formConfig = f.formConfig
  console.log(res)
  res.fieldList.forEach((item) => {
    if (item.navigational) {
      rightSpan.value = 18
      leftSpan.value = 6
      navigationals.value.push(item)
    }
    fieldList.value.push({
      key: item.id,
      label: item.fieldDesc
    })
  })
}
const optionData = ref({})
const formJson = ref({
  widgetList: [],
  formConfig: {}
})
let updated = false
const vFormRef = ref<any>()
const formTitle = ref('修改')
const updateId = ref(0)
const showFormDialogFlag = ref(false)
const updateResource = async (rid) => {
  updated = true
  updateId.value = rid
  showFormDialogFlag.value = true
  let res = await metaApi.selectMetaDataOne(id, rid)
  let formDataJson = await vFormRef.value.setFormData(res)
}
const closeForm = () => {
  //清空表单
  vFormRef.value.resetForm()
  showFormDialogFlag.value = false
}

/** 选择框更变取值 */
const handleOptionChange = async (value) => {
  console.log(value)
}
const formData = ref({
  id: undefined,
  dataIds: undefined,
  metaId: undefined,
  idea: undefined,
  op: '审核通过',
  type: 10
})
const formRules = reactive({
  idea: [{ required: true, message: '审核说明不能为空!', trigger: 'blur' }]
})
const list = ref([])
/** 打开弹窗 */
const open = async (res: List, rowId?) => {
  dialogVisible.value = true
  await resetForm()
  await getList()
  dataIds.value.push(rowId)
  formData.value.metaId = id
  formData.value.type = 10
  list.value.list = res
  list.value.list.forEach((item) => {
    item.create_time = formatDate(item.create_time)
  })
}

const getList = async () => {
  list.value = await metaApi.selectData(id, queryParams).then((res) => {
    res.columns.forEach((item, index) => {
      if (res.columns[index].prop === 'create_time') res.columns.splice(index, 1)
      if (res.columns[index].prop === 'delete_time') res.columns.splice(index, 1)
    })
    return res
  })
  console.log(list.value)
}

const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function isValidJson(str) {
  if (str.startsWith('{') || str.startsWith('[')) {
    if (str.endsWith(']') || str.endsWith('}')) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}
function isNumber(str: string): boolean {
  return /^\d+$/.test(str) // 只包含数字的正则表达式
}

const imaged = (row) => {
  if (!row) {
    return false
  }
  if (isNumber(row)) {
    return false
  }
  return isValidJson(row)
}
const buildImage = (name, row) => {
  if (JSON.parse(row[name]).length > 0) {
    // if (row[name]) {
    return JSON.parse(row[name].replaceAll('\\', ''))[0].url
    // return JSON.parse(row[name])[0].url
  } else {
    return ''
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    dataIds: undefined,
    metaId: undefined,
    idea: undefined,
    op: '送审'
  }
  formRef.value?.resetFields()
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const dataIds = ref([])
const submitAudit = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    console.log(formData.value)
    //调用接口
    formData.value.dataIds = dataIds
    formData.value.op = '驳回'
    await metaApi.back(formData.value)
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  selectForm()
})
defineExpose({ open })
</script>

<style scoped></style>
